package com.service;

import com.entiy.Sentences;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.manager.ChatManager;
import com.selector.ModelSelector;
import com.tool.Message;
import com.tool.ModelData;
import com.tool.Net;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChatService {
    private static final String HOST = "localhost";
    private static final int PORT_11434 = 11434;
    private static final Pattern SENTENCE_PATTERN = Pattern.compile("(?<=[.。!！?？;；…]{1,3})");
    private ModelData currentSession;
    private final Gson gson;
    private Sentences sentences;

    public ChatService() {
        this.gson = new GsonBuilder().create();
        this.sentences = Sentences.getInstance(); // 使用单例实例
    }

    public void initializeNewSession(String model, Scanner scanner) {
        Net net = new Net();
        currentSession = new ModelData(model);
        System.out.print("system : ");
        String m = scanner.nextLine();
        currentSession.getMessages().add(new Message(2,m));
    }

    public void startChatLoop() throws IOException {
        while (true) {
            try {
                URL url = new URL("http://" + HOST + ":" + PORT_11434 + "/api/chat");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json; utf-8");
                conn.setRequestProperty("Accept", "application/json");
                System.out.print("user  :  ");
                String m = new Scanner(System.in).nextLine();
                if("exit".equals(m)){
                    saveChatHistory();
                    System.exit(0);
                }
                currentSession.getMessages().add(new Message(m));
                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = gson.toJson(currentSession).getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                int responseCode = conn.getResponseCode();
                long start = System.currentTimeMillis();
                long token = 0L;
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = conn.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                    StringBuilder sb = new StringBuilder();
                    String inputLine;

                    while ((inputLine = in.readLine()) != null) {
                        JsonObject jsonObject = gson.fromJson(inputLine, JsonObject.class);
                        if (jsonObject.has("done") && !jsonObject.get("done").getAsBoolean()) {
                            token++;

                            inputLine = inputLine.substring(inputLine.indexOf("\"content\":\"") + 11, inputLine.length() - 16);
                            inputLine = inputLine.replace("\\u003c", "<");
                            inputLine = inputLine.replace("\\u003e", ">");
                            inputLine = inputLine.replace("\\n", "\n");
                            System.out.print(inputLine);
                            sb.append(inputLine);
                            // 将新内容追加到缓冲区
                            sentences.setBuffer(inputLine);
                            splitIntoSentences(sentences.getBuffer());
                        }
                    }
                    currentSession.getMessages().add(new Message(0,sb.toString()));
                    in.close();
                    long end = System.currentTimeMillis();
                    System.out.println("\n*****************************************");
                    System.out.println("|\t总耗时：" + ((end - start) / 1000) + "s");
                    System.out.println("|\t总共输出token：" + token);
                    double t = (end - start)/1000.0;
                    System.out.println("|\t平均每秒输出token：" + token / t);
                    System.out.println("*****************************************");
                } else {
                    System.out.println(gson.toJson(currentSession));
                    System.out.println("失败" + responseCode);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    public void loadChatHistory() throws IOException {
        try (Reader reader = new FileReader("E:/develop/code/learnjava/ChatModels/src/main/resources/history/" + ChatManager.getFileName())) {
            currentSession = gson.fromJson(reader, ModelData.class);
        }
    }

    public void saveChatHistory() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("是否保存聊天记录(y/n):");
        if (scanner.nextLine().equalsIgnoreCase("y")) {
            String path = "E:/develop/code/learnjava/ChatModels/src/main/resources/history/";
            File[] files = new File(path).listFiles((dir, name) -> name.endsWith(".json"));
            String fileName = path + "chat_" + files.length + ".json";
            if (ChatManager.isLoadHistory){
                fileName = path + ChatManager.getFileName();
            }
            try (Writer writer = new FileWriter(fileName)) {
                gson.toJson(currentSession, writer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void splitIntoSentences(StringBuilder sb) {
        // 去除特殊字符（如 ★〜☆ ～♪）
        String text = sb.toString().replaceAll("[★〜☆～♪*]", "");

        Matcher matcher = SENTENCE_PATTERN.matcher(text);
        int lastEnd = 0;

        while (matcher.find()) {
            String sentence = text.substring(lastEnd, matcher.start()).trim();
            if (!sentence.isEmpty()) {
                this.sentences.addSentence(sentence); // 将句子加入列表
            }
            lastEnd = matcher.end();
        }
        String remainingText = text.substring(lastEnd).trim();
        if (!remainingText.isEmpty()) {
            sb.setLength(0);
            sb.append(remainingText);
        } else {
            sb.setLength(0);
        }
    }
}